/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.ibatis.extension.keygen;

import com.je.ibatis.extension.toolkit.Constants;
import com.je.ibatis.extension.toolkit.ParameterUtil;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.ExecutorException;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

/**
 * 元数据自增主键策略
 * <p>
 * 插入后获取自增主键,加入parameter的Map中
 *
 * @author wangmm@ketr.com.cn
 * @date 2019/11/21
 */
public class MetaAutoKeyGenerator extends BaseMetaKeyGenerator {

    private static final String BATCH_ID = "!MetaBaseMapper.insertBatch";

    public MetaAutoKeyGenerator(String tableCode, String keyColumns) {
        super(tableCode, keyColumns);
    }

    @Override
    public void processBefore(Executor executor, MappedStatement ms, Statement stmt, Object parameter) {
        // do nothing
    }

    @Override
    public void processAfter(Executor executor, MappedStatement ms, Statement stmt, Object parameter) {
        processBatch(ms, stmt, parameter);
    }

    public void processBatch(MappedStatement ms, Statement stmt, Object parameter) {
        //获取键所在列
        final String[] keyProperties = getKeyProperties();
        if (keyProperties == null || keyProperties.length == 0) {
            return;
        }
        try (ResultSet rs = stmt.getGeneratedKeys()) {
            final ResultSetMetaData rsmd = rs.getMetaData();
            final Configuration configuration = ms.getConfiguration();
            final MetaObject metaParam = configuration.newMetaObject(parameter);
            if (rsmd.getColumnCount() < keyProperties.length) {
                throw new RuntimeException("generated key length don't equals keyProperties length!");
            } else {
                if (rs.next()) {
                    for (int i = 0; i < keyProperties.length; i++) {
                        String keyProperty = keyProperties[i];
                        Object keyValue = rs.getObject(i + 1);
                        ParameterUtil.setValue(metaParam, keyProperty, keyValue);
                        ParameterUtil.setValue(metaParam, Constants.KEY_PK_VALUE, keyValue);
                    }
                } else {
                    throw new RuntimeException("rs.next() is false!");
                }
            }
        } catch (Exception e) {
            throw new ExecutorException("Error getting generated key or setting result to parameter object. Cause: " + e, e);
        }
    }
}
